package com.paimeng.controller;

import com.google.gson.Gson;
import com.paimeng.bean.News_info;
import com.paimeng.lucence.Searcher;
import com.paimeng.utils.SortByHotIndex;
import com.paimeng.utils.SortByTime;
import org.apache.lucene.queryparser.classic.ParseException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


/**
 * @author: 潘辉
 * @Title: SearchHotNews
 * @ProjectName: paimeng
 * @Description: 依据索引中的热点指数查找热点指数最高的几条新闻在首页展示
 * @date: 2021/6/9 19:13
 */
public class SearchHotNewsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    @SuppressWarnings("unchecked")
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();

        String queryStr = request.getParameter("queryStr");
        String sortMethod = request.getParameter("sortnews");
        //System.out.println("queryStr:" + queryStr + "\t" + "sortMethod:" + sortMethod);

        String indexPath = request.getServletContext().getRealPath("/index");
        //System.out.println(indexPath);
        List<News_info> results = null;
        try {
            results = Searcher.searchHot(indexPath, queryStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if ("byHotIndex".equals(sortMethod)) {
            assert results != null;
            results.sort(new SortByHotIndex());
        }
        if ("byTime".equals(sortMethod)) {
            //System.out.println("按时间排序");
            assert results != null;
            results.sort(new SortByTime());
        }

        Gson gson = new Gson();
        String info = gson.toJson(results);

        //System.out.println("贺坤"+info);
        out.print(info);
        out.flush();
        out.close();

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
